package org.crud4j.wicket.markup.html.editor;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.wicket.model.IModel;
import org.crud4j.core.CrudField;
import org.crud4j.core.CrudService;

public class DateModel implements IModel {

	private CrudField field;

	private DateFormat format = new SimpleDateFormat(CrudService.DATE_PATTERN);

	public DateModel(CrudField field) {
		super();
		this.field = field;
	}

	public Object getObject() {
		if (field.getValue() == null || field.getValue().length() == 0) {
			return null;
		} else {
			try {
				return format.parse(field.getValue());
			} catch (ParseException e) {
				throw new RuntimeException("unable to format date field "
						+ field.getDef().getName());
			}
		}
	}

	public void setObject(Object object) {
		field.setValue(format.format((Date) object));

	}

	public void detach() {
	}

	public CrudField getField() {
		return field;
	}

}
